package com.sky.service.impl;

import com.sky.entity.Dish;
import com.sky.entity.Orders;
import com.sky.entity.Setmeal;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.WorkSpaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
@Slf4j
public class WorkSpaceServiceImpl implements WorkSpaceService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 获取今日数据
     *
     * @return
     */
    @Override
    public BusinessDataVO getTodayData() {
        /**
         * 今日数据
         * + 营业额（已完成订单的总金额）
         * + 有效订单（已完成订单的数量）
         * + 订单完成率（有效订单数/总订单数 * 100%）
         * + 平均客单价（营业额/有效订单数）
         * + 新增用户（新增用户的数量）
         */
        // 1. 获取当日的日期
        LocalDate today = LocalDate.now();
        // 2. 以当日日期为条件查询营业额、有效订单数、新增用户数
        LocalDateTime beginTime = LocalDateTime.of(today, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(today, LocalTime.MAX);
        return getData(beginTime, endTime);
    }

    /**
     * 获取某日数据
     *
     * @return
     */
    @Override
    public BusinessDataVO getBusinessData(LocalDateTime beginTime, LocalDateTime endTime) {
        return getData(beginTime, endTime);
    }

    /**
     * 获取订单管理数据
     *
     * @return
     */
    @Override
    public OrderOverViewVO getOverViewOrder() {

        // 以状态为条件进行订单查询(今日)
        // 1. 待接单
        Integer waitingOrders = orderCount(Orders.REFUND);
        // 2. 待派送(已接单)
        Integer deliveredOrders = orderCount(Orders.CONFIRMED);
        // 3. 已完成
        Integer completedOrders = orderCount(Orders.COMPLETED);
        // 4. 已取消
        Integer cancelledOrders = orderCount(Orders.CANCELLED);
        // 5. 全部订单
        Integer allOrders = orderCount(null);

        return OrderOverViewVO.builder()
                .waitingOrders(waitingOrders)
                .deliveredOrders(deliveredOrders)
                .completedOrders(completedOrders)
                .cancelledOrders(cancelledOrders)
                .allOrders(allOrders)
                .build();
    }

    /**
     * 获取菜品总览数据
     *
     * @return
     */
    @Override
    public DishOverViewVO getOverViewDish() {
        // 1. 已起售数量
        Integer sold = dishMapper.getDishByStatus(Dish.STATUS_ENABLE);
        // 2. 已停售数量
        Integer discontinued = dishMapper.getDishByStatus(Dish.STATUS_DISABLE);

        return DishOverViewVO.builder()
                .sold(sold)
                .discontinued(discontinued)
                .build();
    }

    /**
     * 获取套餐总览数据
     *
     * @return
     */
    @Override
    public SetmealOverViewVO getOverViewSetMeal() {
        // 1. 已起售数量
        Integer sold = setmealMapper.countByStatus(Setmeal.STATUS_ENABLE);
        // 2. 已停售数量
        Integer discontinued = setmealMapper.countByStatus(Setmeal.STATUS_DISABLE);

        return SetmealOverViewVO.builder()
                .sold(sold)
                .discontinued(discontinued)
                .build();
    }

    /**
     * 获取订单数量
     *
     * @param status 订单状态
     * @return
     */
    public Integer orderCount(Integer status) {
        // 获取当日日期
        LocalDateTime beginTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);

        Map<String, Object> map = new HashMap<>();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("status", status);
        return orderMapper.orderByOrderTime(map);
    }

    /**
     * 抽取方法
     * @param beginTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    public BusinessDataVO getData(LocalDateTime beginTime, LocalDateTime endTime) {
        /**
         * 今日数据
         * + 营业额（已完成订单的总金额）
         * + 有效订单（已完成订单的数量）
         * + 订单完成率（有效订单数/总订单数 * 100%）
         * + 平均客单价（营业额/有效订单数）
         * + 新增用户（新增用户的数量）
         */
        Map<String, Object> map = new HashMap<>();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("status", Orders.COMPLETED);
        // 2.1 营业额
        Double turnover = orderMapper.sumByOrderTimeBetween(map);
        if (turnover == null) {
            turnover = 0.0;
        }
        // 2.2 有效订单数
        Integer validOrderCount = orderCount(Orders.COMPLETED);
        // 2.3 订单完成率
        // 总订单
        Integer totalOrderCount = orderCount(null);
        Double orderCompletionRate = totalOrderCount == 0 ? 0.0 : validOrderCount.doubleValue() / totalOrderCount;
        // 2.4 平均客单价
        Double unitPrice = validOrderCount == 0 ? 0.0 : turnover / validOrderCount;
        // 2.5 新增用户数
        Integer newUsers = userMapper.getUserCountForTime(beginTime, endTime);
        return BusinessDataVO.builder()
                .turnover(turnover)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .unitPrice(unitPrice)
                .newUsers(newUsers)
                .build();
    }
}
